package com.thinkfit.jy.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.view.View;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.blankj.utilcode.util.AppUtils;
import com.common.lib.bean.UserBean;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.common.lib.view.CircularProgressView;
import com.github.mikephil.charting.charts.LineChart;
import com.thinkfit.jy.R;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.serialport.SportType;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DateUtils;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.FastBlurUtility;
import com.thinkfit.jy.utils.LineChartUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.disposables.Disposable;

public class FreeMovementActivity extends MainActivity {

    private ActivityResultLauncher mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                mTargetType = result.getData().getIntExtra(Constants.BUNDLE_EXTRA, 0);
                mTargetNum = result.getData().getIntExtra(Constants.BUNDLE_EXTRA_2, 0);
                showTarget();
            }
        }
    });

    private int mTargetType = 0;  //0表示时间 1表示距离 2表示kcal
    private int mTargetNum;
    private int mType;//0目标训练，1自由运动
    private boolean mIsTargetComplete;
    private int mMainStyle;

    private boolean isShowLine = false;


    LineChartUtils lineChartUtils = new LineChartUtils(this);;
    LineChartUtils lineChartUtils1 = new LineChartUtils(this);;
    LineChartUtils lineChartUtils2 = new LineChartUtils(this);;
    LineChartUtils lineChartUtils3 = new LineChartUtils(this);;

    @Override
    protected int getLayoutId() {
        mMainStyle = DataManager.Companion.getInstance().getMainStyle();
        return mMainStyle == 3 ? R.layout.activity_free_movement_xm : R.layout.activity_free_movement;
    }
    public void init() {
        if(DeviceTypeUtils.connectDeviceType() == 0){
            BluetoothOrder.getInstance().setSportType(SportType.FREE);
        }else {
            SerialPortManager.getInstance().setSportType(SportType.FREE, -1);
        }

        mType = getIntent().getExtras().getInt(Constants.BUNDLE_EXTRA, 0);
        switch (mType) {
            case 0:
                findViewById(R.id.llTop).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                            DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(FreeMovementActivity.this));
                        }
                        Intent intent = new Intent(FreeMovementActivity.this, SetTargetActivity.class);
                        intent.putExtra(Constants.BUNDLE_EXTRA, 0);
                        mLauncher.launch(intent);
                    }
                }, 500);
                break;
            case 1://自由运动
                setViewGone(R.id.llAdd);
                setViewVisible(R.id.tvFreeSport);
                break;
        }
        resetDate();
//        if(DeviceTypeUtils.connectDeviceType() == 0){
//            if(MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING)
//            ||MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.ELLIPTICAL_MACHINE)){
//                //动感单车或椭圆机
//                initSpinning();
//            } else if (MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
//                //划船机
//                initRowingMachine();
//            }else if(MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
//                //跑步机
//                initTreadmill();
//            }
//
//        }else {
//            if (SerialPortManager.mCurrentDeviceType == DeviceType.CAR_WATCH) {
//                initRowingMachine();
//            } else {
//                setViewsOnClickListener(R.id.tvSpeed1, R.id.tvSpeed2, R.id.tvSpeed3, R.id.tvSpeed4);
//            }
//        }

        if(MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING)
                ||MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.ELLIPTICAL_MACHINE)){
            //动感单车或椭圆机
            initSpinning();
        } else if (MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
            //划船机
            initRowingMachine();
        }else if(MotionDataUtils.getInstance().mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
            //跑步机
            initTreadmill();
        }

        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
        if (myInfo == null) {
            setViewVisible(R.id.tvNotLogin);
            setViewGone(R.id.ivAvatar, R.id.tvUseName);
        } else {
            setViewGone(R.id.tvNotLogin);
            setViewVisible(R.id.ivAvatar, R.id.tvUseName);
            setText(R.id.tvUseName, myInfo.getNickname());
            BaseUtils.StaticParams.loadImage(this, R.drawable.app_not_login, myInfo.getHeadimg(), findViewById(R.id.ivAvatar));
        }
        setViewsOnClickListener(R.id.ivAvatar, R.id.ivHome, R.id.ivBack, R.id.ivSound,
                R.id.ivSlopMinus, R.id.ivSlopAdd, R.id.ivSpeedMinus, R.id.ivSpeedAdd,
                R.id.tvSlop1, R.id.tvSlop2, R.id.tvSlop3, R.id.tvSlop4,R.id.iv_app,R.id.iv_line,
                R.id.tvAddTime, R.id.tvAddDistance, R.id.tvAddKcal, R.id.llStart,R.id.ivBluetooth);
        setLinearGradient(R.id.tv0_1, Color.parseColor("#E96D88"), Color.parseColor("#D14782"));
        setLinearGradient(R.id.tv1_1, Color.parseColor("#EFC638"), Color.parseColor("#F7A736"));
        setLinearGradient(R.id.tv2_1, Color.parseColor("#628FEA"), Color.parseColor("#9B7FCA"));
        setLinearGradient(R.id.tv3_1, Color.parseColor("#4BD8C8"), Color.parseColor("#33A1A6"));
        setLinearGradient(R.id.tv4_1, Color.parseColor("#72C0E4"), Color.parseColor("#7075C3"));
        setLinearGradient(R.id.tv5_1, Color.parseColor("#E77760"), Color.parseColor("#F66467"));
        setLinearGradient(R.id.tv1, Color.parseColor("#72C0E4"), Color.parseColor("#3670C7"));
        setLinearGradient(R.id.tvSlopUnit, Color.parseColor("#EFC638"), Color.parseColor("#F7A736"));
        setLinearGradient(R.id.tvSpeedUnit, Color.parseColor("#EFC638"), Color.parseColor("#F7A736"));
        setTextTypeFace(R.id.tvKcal, R.id.tvSteps, R.id.tvSpm, R.id.tvSpeed, R.id.tvSlope,
                R.id.tv2, R.id.tvKm, R.id.tvPace, R.id.tvBpm, R.id.tvNum,
                R.id.tvSlop1, R.id.tvSlop2, R.id.tvSlop3, R.id.tvSlop4,
                R.id.tvSpeed1, R.id.tvSpeed2, R.id.tvSpeed3, R.id.tvSpeed4);
        resetDate();
        if(DataManager.Companion.getInstance().getUnit()){
            setText(R.id.tv3_1,getString(R.string.app_mi));
            setText(R.id.tv4_1,getString(R.string.app_min_mi));
        }else {
            setText(R.id.tv3_1,getString(R.string.app_km));
            setText(R.id.tv4_1,getString(R.string.app_min_km));
        }
        if(DeviceTypeUtils.isConnect()){
            resetInfo(MotionDataUtils.getInstance().getCurrentInfo());
        }
        System.out.println("ddddddddddddddddddddddd   isRun  :  " + DeviceTypeUtils.connectDeviceType());
        System.out.println("ddddddddddddddddddddddd   isRun 333 :  " + MotionDataUtils.getInstance().isRun());
        showStartBtn(MotionDataUtils.getInstance().isRun());
        LineChart lc1 = findViewById(R.id.lc_1);
        LineChart lc2 = findViewById(R.id.lc_2);
        LineChart lc3 = findViewById(R.id.lc_3);
        LineChart lc4 = findViewById(R.id.lc_4);
        lineChartUtils.initView(lc1);
        lineChartUtils1.initView(lc2);
        lineChartUtils2.initView(lc3);
        lineChartUtils3.initView(lc4);

//        float[] f = new float[]{5,6,7,3,5,4,7,6,10,12,15,4,9,17,10,5,6,7,6,3,6,7,5,10,15,6,10,3,5,10};
//        Observable.interval(1000, TimeUnit.MILLISECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<Long>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        disposable = d;
//                    }
//
//                    @Override
//                    public void onNext(Long aLong) {
//                        BigDecimal numBigDecimal = new BigDecimal(aLong);
//                        // 或 numBigDecimal = BigDecimal.valueOf(numberLong);
//                        int numberInt = numBigDecimal.intValue();
//                        if(numberInt >= f.length){
//                            if (disposable != null) {
//                                disposable.dispose();
//                                disposable = null;
//                            }
//                            return;
//                        }
//                        lineChartUtils.invalidate(numberInt,f[numberInt]);
//                        lineChartUtils1.invalidate(numberInt,f[numberInt]);
//                        lineChartUtils2.invalidate(numberInt,f[numberInt]);
//                        lineChartUtils3.invalidate(numberInt,f[numberInt]);
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });

    }
    Disposable disposable;
    public void initRowingMachine() {
        setImage(R.id.iv1_0, R.drawable.app_pulp);
        setText(R.id.tv1_0, R.string.app_pulp_count);
        setText(R.id.tv1_1, "-");
        setImage(R.id.iv2_0, R.drawable.app_pulp_rate);
        setText(R.id.tv2_0, R.string.app_pulp_rate);
        setText(R.id.tv4_1, R.string.app_per_500m);
        setText(R.id.tv, R.string.app_resistance);
        setText(R.id.tv2, R.string.app_pace_500m);
        setViewInvisible(R.id.ivSpeedAdd, R.id.ivSpeedMinus);
        if (EquipmentInfoUtils.getInstance().getResistance() > 0) {
            int resistance = EquipmentInfoUtils.getInstance().getResistance();
            int i = resistance / 4;
            setText(R.id.tvSlop1, resistance+"");
            setText(R.id.tvSlop2, (i*2)+"");
            setText(R.id.tvSlop3, i+"");
            setText(R.id.tvSlop4, "1");
        }else {
            setText(R.id.tvSlop1, "-");
            setText(R.id.tvSlop2, "-");
            setText(R.id.tvSlop3, "-");
            setText(R.id.tvSlop4, "-");
        }
        setText(R.id.tvSpeed1, "-");
        setText(R.id.tvSpeed2, "-");
        setText(R.id.tvSpeed3, "-");
        setText(R.id.tvSpeed4, "-");
        setText(R.id.tvSpeedUnit, "-");
    }

    public void initSpinning(){
        setImage(R.id.iv1_0, R.drawable.app_step);
        setText(R.id.tv1_0, R.string.app_speed_count);
        setText(R.id.tv1_1, R.string.app_speeds);
        setImage(R.id.iv2_0, R.drawable.app_step_rate);
        setText(R.id.tv2_0, R.string.app_speed_rate);
        setText(R.id.tv2_1, R.string.app_rpm);
        setText(R.id.tv, R.string.app_resistance);
        if(DataManager.Companion.getInstance().getUnit()){
            setText(R.id.tv4_1, R.string.app_min_mi);
            setText(R.id.tv2, R.string.app_speed_mi);
        }else {
            setText(R.id.tv4_1, R.string.app_min_km);
            setText(R.id.tv2, R.string.app_speed);
        }
        setViewInvisible(R.id.ivSpeedAdd, R.id.ivSpeedMinus);
        if (EquipmentInfoUtils.getInstance().getResistance() > 0) {
            int resistance = EquipmentInfoUtils.getInstance().getResistance();
            int i = resistance / 4;
            setText(R.id.tvSlop1, resistance+"");
            setText(R.id.tvSlop2, (i*2)+"");
            setText(R.id.tvSlop3, i+"");
            setText(R.id.tvSlop4, "1");
        }else {
            setText(R.id.tvSlop1, "-");
            setText(R.id.tvSlop2, "-");
            setText(R.id.tvSlop3, "-");
            setText(R.id.tvSlop4, "-");
        }

        setText(R.id.tvSpeed1, "-");
        setText(R.id.tvSpeed2, "-");
        setText(R.id.tvSpeed3, "-");
        setText(R.id.tvSpeed4, "-");
        setText(R.id.tvSpeedUnit, "-");
    }

    /**
     * 跑步机
     */
    public void initTreadmill(){
        setText(R.id.tv0_0,R.string.app_use_up);//消耗标题
        setText(R.id.tvKcal,0+"");//消耗
        setImage(R.id.iv1_0,R.drawable.app_step);//跑步图片
        setText(R.id.tv1_0,R.string.app_speed_count);//步数单位
        setText(R.id.tv1_1,R.string.app_speeds);//步数英文
        setText(R.id.tvSteps,0+"");//步数
        setImage(R.id.iv2_0, R.drawable.app_step_rate);
        setText(R.id.tv2_0,R.string.app_step_rate);//步频标题
        setText(R.id.tv2_1,R.string.app_spm);//步频单位
        setText(R.id.tvSpm,0+"");//步频
        setText(R.id.tv3_0,R.string.app_distance_1);//距离标题
        if(DataManager.Companion.getInstance().getUnit()){
            setText(R.id.tv3_1,R.string.app_mi);//距离单位
            setText(R.id.tv4_1,R.string.app_min_mi);//配速单位
            setText(R.id.tv2,R.string.app_speed_mi);//速度单位
        }else {
            setText(R.id.tv3_1,R.string.app_km);//距离单位
            setText(R.id.tv4_1,R.string.app_min_km);//配速单位
            setText(R.id.tv2,R.string.app_speed);//速度单位
        }
        setText(R.id.tvKm,0+"");//距离
        setText(R.id.tv4_0,R.string.app_pace);//配速标题
        setText(R.id.tvPace,0+"");//配速
        setText(R.id.tv5_0,R.string.app_heart_rate);//心率标题
        setText(R.id.tv5_1,R.string.app_bpm);//心率单位
        setText(R.id.tvBpm,0+"");//心率单位
        setText(R.id.tv,R.string.app_slope);//坡度单位
        setText(R.id.tvSlope,0+"");//坡度
        setText(R.id.tvSpeed,0+"");//速度
        System.out.println(TAG +" ddddddddddddddddddddddd    speed   "+ EquipmentInfoUtils.getInstance().getResistance());
        if (EquipmentInfoUtils.getInstance().getResistance() > 0) {
            int resistance = EquipmentInfoUtils.getInstance().getResistance();
            int i = resistance / 4;
            setText(R.id.tvSpeed1, (resistance/10)+"");
            setText(R.id.tvSpeed2, ((i*2)/10)+"");
            setText(R.id.tvSpeed3, (i/10)+"");
            setText(R.id.tvSpeed4, "0.1");
        }else {
            setText(R.id.tvSpeed1, "-");
            setText(R.id.tvSpeed2, "-");
            setText(R.id.tvSpeed3, "-");
            setText(R.id.tvSpeed4, "-");
        }
        System.out.println(TAG +" ddddddddddddddddddddddd    slope   "+ EquipmentInfoUtils.getInstance().getSlop());
        if(EquipmentInfoUtils.getInstance().getEquipmentInfoBean() != null){
            if(EquipmentInfoUtils.getInstance().getEquipmentInfoBean().getSlope() > 0){
                int slope = EquipmentInfoUtils.getInstance().getEquipmentInfoBean().getSlope();

                int i = slope / 4;
                setText(R.id.tvSlop1, slope+"");
                setText(R.id.tvSlop2, (i*2)+"");
                setText(R.id.tvSlop3, i+"");
                setText(R.id.tvSlop4, "1");
            }else {
                setText(R.id.tvSlop1, "-");
                setText(R.id.tvSlop2, "-");
                setText(R.id.tvSlop3, "-");
                setText(R.id.tvSlop4, "-");
            }
        }
        setViewsOnClickListener(R.id.tvSpeed1, R.id.tvSpeed2, R.id.tvSpeed3, R.id.tvSpeed4);
    }

    /**
     * 停止初始化控件
     */
    public void initWidget(){
//        if (DeviceTypeUtils.connectDeviceType() == 0) {
//            if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
//                setText(R.id.tvPace, "00:00");
//                setText(R.id.tvSpeed, "00:00");
//            }else {
//                setText(R.id.tvPace, "0");
//                setText(R.id.tvSpeed, "0");
//            }
//
//        }else {
//            if(SerialPortManager.mCurrentDeviceType == DeviceType.CAR_WATCH){
//                setText(R.id.tvPace, "00:00");
//                setText(R.id.tvSpeed, "00:00");
//
//            }else {
//                setText(R.id.tvSpeed, "0");
//                setText(R.id.tvPace, "0");
//            }
//        }
        if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
            setText(R.id.tvPace, "00:00");
            setText(R.id.tvSpeed, "00:00");
        }else {
            setText(R.id.tvPace, "0");
            setText(R.id.tvSpeed, "0");
        }
        setText(R.id.tvSlope, "0");
        setText(R.id.tvNum, "00:00");
        setText(R.id.tvKcal, "0");
        setText(R.id.tvSteps, "0");
        setText(R.id.tvSpm, "0");
        setText(R.id.tvKm, "0");
        setText(R.id.tvBpm, "0");
        CircularProgressView progressView = findViewById(R.id.circularProgressView);
        progressView.setProgress(0);
        if(DeviceTypeUtils.connectDeviceType() == 0){
            BluetoothOrder.getInstance().closeCurrentInfo();
        }else {
            SerialPortManager.getInstance().closeCurrentInfo();
        }
        time = 0;
        lineChartUtils.clearValues();
        lineChartUtils1.clearValues();
        lineChartUtils2.clearValues();
        lineChartUtils3.clearValues();
    }



    private void showTarget() {
        if (mTargetNum <= 0) {
            setViewInvisible(R.id.tvTarget);
        } else {
            setViewVisible(R.id.tvTarget);
            switch (mTargetType) {
                case 0:
                    setLinearGradient(R.id.tv1, Color.parseColor("#72C0E4"), Color.parseColor("#3670C7"));
                    setText(R.id.tv0, R.string.app_time);
                    setText(R.id.tv1, R.string.app_min_sec);
                    setText(R.id.tvNum, "00:00");
                    setText(R.id.tvTarget, getString(R.string.app_target_xxx_minutes, String.valueOf(mTargetNum)));
                    setImage(R.id.iv, R.drawable.app_time_icon);
                    break;
                case 1:
                    setLinearGradient(R.id.tv1, Color.parseColor("#4BD8C8"), Color.parseColor("#33A1A6"));
                    setText(R.id.tv0, R.string.app_distance);
                    setText(R.id.tv1, R.string.app_km);
                    setText(R.id.tvNum, "0");
                    setText(R.id.tvTarget, getString(R.string.app_target_xxx_km, String.valueOf(mTargetNum)));
                    setImage(R.id.iv, R.drawable.app_km_icon);
                    break;
                case 2:
                    setLinearGradient(R.id.tv1, Color.parseColor("#E96D88"), Color.parseColor("#D14782"));
                    setText(R.id.tv0, R.string.app_use_up);
                    setText(R.id.tv1, R.string.app_kcal);
                    setText(R.id.tvNum, "0");
                    setText(R.id.tvTarget, getString(R.string.app_target_xxx_kcal, String.valueOf(mTargetNum)));
                    setImage(R.id.iv, R.drawable.app_kcal_icon);
                    break;
            }
        }
        mIsTargetComplete = false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
//                if (SerialPortManager.getInstance().isRun()|| BluetoothOrder.getInstance().isRun()) {
//                    if(DeviceTypeUtils.connectDeviceType() == 0){
//                        BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_STOP);
//                    }else {
//                        SerialPortManager.getInstance().stopRun();
//                    }
//                    finish();
//                    return;
//                }
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                Intent intent = new Intent(this, DialogActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.END_SPORT_BACK);
                startActivity(intent);
                break;
            case R.id.ivHome:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                intent = new Intent(this, DialogActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.END_SPORT_TO_HOME);
                startActivity(intent);
                break;
            case R.id.tvSlop1:
//                resetSlopBtn(1);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                setEqSlop(Integer.parseInt(getTextById(R.id.tvSlop1)));
                break;
            case R.id.tvSlop2:
//                resetSlopBtn(2);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }

                setEqSlop(Integer.parseInt(getTextById(R.id.tvSlop2)));
                break;
            case R.id.tvSlop3:
//                resetSlopBtn(3);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                setEqSlop(Integer.parseInt(getTextById(R.id.tvSlop3)));

                break;
            case R.id.tvSlop4:
//                resetSlopBtn(4);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                setEqSlop(Integer.parseInt(getTextById(R.id.tvSlop4)));
                break;
            case R.id.tvSpeed1:
                resetSpeedBtn(1);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                setEqSpeed(Integer.parseInt(getTextById(R.id.tvSpeed1))*10);
                break;
            case R.id.tvSpeed2:
                resetSpeedBtn(2);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                setEqSpeed(Integer.parseInt(getTextById(R.id.tvSpeed2))*10);
                break;
            case R.id.tvSpeed3:
                resetSpeedBtn(3);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                setEqSpeed(Integer.parseInt(getTextById(R.id.tvSpeed3))*10);
                break;
            case R.id.tvSpeed4:
                resetSpeedBtn(4);
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }

                setEqSpeed((int)Float.parseFloat(getTextById(R.id.tvSpeed4))*10);
                break;
            case R.id.ivSpeedAdd:
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                resetSpeed(true);
                break;
            case R.id.ivSpeedMinus:
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                resetSpeed(false);
                break;
            case R.id.ivSlopAdd:
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                resetSlop(true);
                break;
            case R.id.ivSlopMinus:
                if (!SerialPortManager.getInstance().isConnected()&&!BluetoothOrder.getInstance().isConnect()) {
                    showToast(R.string.app_device_connect);
                    return;
                }
                resetSlop(false);
                break;
            case R.id.tvAddTime:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                intent = new Intent(this, SetTargetActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, 0);
                mLauncher.launch(intent);
                break;
            case R.id.tvAddDistance:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                intent = new Intent(this, SetTargetActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, 1);
                mLauncher.launch(intent);
                break;
            case R.id.tvAddKcal:
                if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                    DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                }
                intent = new Intent(this, SetTargetActivity.class);
                intent.putExtra(Constants.BUNDLE_EXTRA, 2);
                mLauncher.launch(intent);
                break;

            case R.id.iv_line:
                if(isShowLine){
                    isShowLine = false;
                    setViewGone(R.id.cl_line);
                }else {
                    isShowLine = true;
                    setViewVisible(R.id.cl_line);
                }

                break;
            default:
                super.onClick(v);
        }
    }

    public ArrayList<AppUtils.AppInfo> getAppList(){
        ArrayList<AppUtils.AppInfo> list1 = new ArrayList<>();
        PackageManager pm = this.getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        int size = packages.size();
        for (int i = 0; i < size; i++) {
            PackageInfo packageInfo = packages.get(i);
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0 ||
                    packageInfo.packageName.equals(this.getPackageName())) {
                continue;
            }
            list1.add(new AppUtils.AppInfo(
                    packageInfo.packageName,
                    packageInfo.applicationInfo.loadLabel(pm).toString(),
                    packageInfo.applicationInfo.loadIcon(pm),
                    "",
                    packageInfo.versionName,
                    packageInfo.versionCode,
                    false
            ));
        }
        return list1;
    }

    /**
     * 设置速度
     * @param speed
     */
    public void setEqSpeed(int speed){
        if(DeviceTypeUtils.connectDeviceType() == 0){
            if(DeviceTypeUtils.getInstance().isTreadmill()){
                BluetoothOrder.getInstance().setTreadmillSpeedAndSlope(speed, MotionDataUtils.getInstance().getCurrentInfo().slop);
            }else {
                BluetoothOrder.getInstance().setNowelAndSlope(speed, MotionDataUtils.getInstance().getCurrentInfo().slop);
            }

        }else {
            SerialPortManager.getInstance().setSpeedSlop(speed, MotionDataUtils.getInstance().getCurrentInfo().slop);
        }
    }

    /**
     * 设置阻力
     * @param slop
     */
    public void setEqSlop(int slop){
        if(DeviceTypeUtils.connectDeviceType() == 0){
            System.out.println("ddddddddddddddddddddddd"+MotionDataUtils.getInstance().getCurrentInfo().speed);
            if(DeviceTypeUtils.TREADMILL.equals(MotionDataUtils.mCurrentDeviceType)) {
                BluetoothOrder.getInstance().setTreadmillSpeedAndSlope(MotionDataUtils.getInstance().getCurrentInfo().speed,slop);
            }else {
                BluetoothOrder.getInstance().setNowelAndSlope(slop, MotionDataUtils.getInstance().getCurrentInfo().slop);
            }
        }else {
            if (DeviceTypeUtils.TREADMILL.equals(MotionDataUtils.mCurrentDeviceType)) {
                SerialPortManager.getInstance().setSpeedSlop(slop,MotionDataUtils.getInstance().getCurrentInfo().speed);
            } else {
                SerialPortManager.getInstance().setResistanceSlop(slop, MotionDataUtils.getInstance().getCurrentInfo().slop);
            }
        }
    }


    private void resetSpeedBtn(int index) {
//        for (int i = 1; i < 5; ++i) {
//            int id = getResources().getIdentifier("tvSpeed" + i, "id", getPackageName());
//            TextView tv = findViewById(id);
//            if (i == index) {
//                tv.setBackgroundResource(R.drawable.shape_ffffff_tr_br_3);
//                tv.setTextColor(ContextCompat.getColor(this, com.common.lib.R.color.color_2d_2c_2f));
//            } else {
//                tv.setBackgroundResource(mMainStyle == 3 ? R.drawable.shape_2bffffff_tr_br_3 : R.drawable.shape_2d2c2f_tr_br_3);
//                tv.setTextColor(ContextCompat.getColor(this, com.common.lib.R.color.text_color_3));
//            }
//        }
//        setText(R.id.tvSpeed, Utils.getNewFloat(BluetoothOrder.getInstance().getCurrentInfo().speed));
    }

    private void resetSlopBtn(int index) {
//        for (int i = 1; i < 5; ++i) {
//            int id = getResources().getIdentifier("tvSlop" + i, "id", getPackageName());
//            TextView tv = findViewById(id);
//            if (i == index) {
//                tv.setBackgroundResource(R.drawable.shape_ffffff_tr_br_3);
//                tv.setTextColor(ContextCompat.getColor(this, com.common.lib.R.color.color_2d_2c_2f));
//            } else {
//                tv.setBackgroundResource(mMainStyle == 3 ? R.drawable.shape_2bffffff_tr_br_3 : R.drawable.shape_2d2c2f_tr_br_3);
//                tv.setTextColor(ContextCompat.getColor(this, com.common.lib.R.color.text_color_3));
//            }
//        }

//        setText(R.id.tvSlope, Utils.getNewFloat(BluetoothOrder.getInstance().getCurrentInfo().slop));
    }

    /**
     * 设置速度
     * @param isAdd 判断是否是增加
     */
    private void resetSpeed(boolean isAdd) {
        TextView tvSpeed = (TextView) findViewById(R.id.tvSpeed);
        String textById = tvSpeed.getText().toString().trim();
        if(textById.length()>=5){
            return;
        }
        BigDecimal speed = new BigDecimal(getTextById(R.id.tvSpeed));
        if (isAdd) {
            speed = speed.add(new BigDecimal("0.1"));
        } else {
            speed = speed.subtract(new BigDecimal("0.1"));
        }
        if (speed.compareTo(BigDecimal.ZERO) < 0) {
            return;
        }
        int slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
        if(DeviceTypeUtils.connectDeviceType() == 0){
            if(DeviceTypeUtils.getInstance().isTreadmill()){
                BluetoothOrder.getInstance().setTreadmillSpeedAndSlope(speed.intValue(),slop);
            }else {
                BluetoothOrder.getInstance().setNowelAndSlope(speed.intValue(),slop);
            }
        }else {
            SerialPortManager.getInstance().setSpeedSlop(speed.multiply(BigDecimal.TEN).intValue(), slop);
        }

    }

    /**
     * 设置坡度
     * @param isAdd 判断是否是增加
     */
    private void resetSlop(boolean isAdd) {
        BigDecimal value = new BigDecimal(getTextById(R.id.tvSlope));
        if (isAdd) {
            value = value.add(new BigDecimal("1"));
        } else {
            value = value.subtract(new BigDecimal("1"));
        }
        if (value.compareTo(BigDecimal.ZERO) < 0) {
            return;
        }
        if(DeviceTypeUtils.connectDeviceType() == 0){
            if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
                if (value.intValue() < 0) {
                    return;
                }
                int speed = MotionDataUtils.getInstance().getCurrentInfo().speed;
                BluetoothOrder.getInstance().setTreadmillSpeedAndSlope(speed,value.intValue());

            }else {

                if (value.intValue() < 0 || value.intValue() > 32) {
                    return;
                }
                int slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
                BluetoothOrder.getInstance().setNowelAndSlope(value.intValue(), slop);
            }
        }else {
            if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)) {
                if (value.intValue() < 0) {
                    return;
                }
                int speed = MotionDataUtils.getInstance().getCurrentInfo().speed;
                SerialPortManager.getInstance().setSpeedSlop(speed, value.intValue());
            } else {
                if (value.intValue() < 0 || value.intValue() > 32) {
                    return;
                }
                int slop = MotionDataUtils.getInstance().getCurrentInfo().slop;
                SerialPortManager.getInstance().setResistanceSlop(value.intValue(), slop);
            }
        }
    }

    int time = 0;

    /**
     * 刷新内容
     * @param info
     */
    public void resetInfo(SerialPortManager.CurrentInfo info) {
        setText(R.id.tvKm, Utils.getNewFloat2(info.distance / 1000f));
        setText(R.id.tvBpm, String.valueOf(info.heart));
        float valY = 0f,valY2 = 0f;

        if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
            setText(R.id.tvKcal, Utils.getNewFloat(info.kcal * 1.0f / 1000));
            setText(R.id.tvSteps, String.valueOf(info.count));
            setText(R.id.tv_lc_slop,getString(R.string.app_slope));
            setText(R.id.tv_lc_spm,getString(R.string.app_step_rate));
            setText(R.id.tvSpm, String.valueOf(0));
            setText(R.id.tvSlope, Utils.getNewFloat(info.slop));
            valY2 = Float.parseFloat(Utils.getNewFloat(info.slop));
//                lineChartUtils2.invalidate(info.time,Float.parseFloat(Utils.getNewFloat(info.slop)));
            if(DataManager.Companion.getInstance().getUnit()){
                setText(R.id.tvSpeed, Utils.getNewFloat(info.speed / 16f));
                valY = Float.parseFloat(Utils.getNewFloat(info.speed / 16f));
//                    lineChartUtils.invalidate(info.time,Float.parseFloat(Utils.getNewFloat(info.speed / 16f)));
                setText(R.id.tvKm, String.valueOf(info.distance/1.6f));
                setText(R.id.tvPace, info.speed == 0 ? "0" : Utils.getNewFloat2(60f / (info.speed / 16f)));   //计算多少分钟跑1英里
            }else {
                setText(R.id.tvSpeed, Utils.getNewFloat(info.speed / 10f));
                valY = Float.parseFloat(Utils.getNewFloat(info.speed / 10f));
//                    lineChartUtils.invalidate(info.time,Float.parseFloat(Utils.getNewFloat(info.speed / 10f)));
                setText(R.id.tvKm, String.valueOf(info.distance));
                setText(R.id.tvPace, info.speed == 0 ? "0" : Utils.getNewFloat2(60f / (info.speed / 10f)));   //计算多少分钟跑1公里
            }

        }else if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING)){
            setText(R.id.tvKcal, Utils.getNewFloat(info.kcal * 0.1f));
            setText(R.id.tvSteps, String.valueOf(info.count));
            setText(R.id.tvSpm, String.valueOf(info.rpm));
            setText(R.id.tvSlope, String.valueOf(info.slop));
            setText(R.id.tv_lc_slop,getString(R.string.app_resistance));
            setText(R.id.tv_lc_spm,getString(R.string.app_speed_rate));
            valY2 = info.slop;
//                lineChartUtils2.invalidate(info.time,info.slop);
            String text;
            if (info.speed == 0) {
                text = "00:00";
            } else {
                text = DateUtils.getInstance().speedKmMin(info.speed);
            }
            setText(R.id.tvSpeed, Utils.getNewFloat(info.speed*0.01f));
            valY = Float.parseFloat(Utils.getNewFloat(info.speed*0.01f));
//                lineChartUtils.invalidate(info.time,Float.parseFloat(Utils.getNewFloat(info.speed*0.01f)));
            setText(R.id.tvPace, text);
        }else if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
            setText(R.id.tvKcal, Utils.getNewFloat(info.kcal * 0.1f));
            setText(R.id.tvSteps, String.valueOf(info.count));
            setText(R.id.tvSpm, String.valueOf(info.rpm));
            setText(R.id.tvSlope, String.valueOf(info.slop));
            setText(R.id.tv_lc_slop,getString(R.string.app_resistance));
            setText(R.id.tv_lc_spm,getString(R.string.app_pulp_rate));
            valY2 = Float.parseFloat(String.valueOf(info.slop));
//                lineChartUtils2.invalidate(info.time,Float.parseFloat(String.valueOf(info.resistance)));
            String text;
            if (info.speed == 0) {
                text = "00:00";
            } else {
                text = DateUtils.getInstance().speedAllocationConvertInto(info.speed);
            }
            valY = Float.parseFloat(Utils.getNewFloat(info.speed*0.01f));
            setText(R.id.tvSpeed, text);
            setText(R.id.tvPace, text);
        }

//        if(DeviceTypeUtils.connectDeviceType() == 0){
//
////            showSpeedViewUtils.setInfo(Utils.getNewFloat(info.speed*0.01f),Utils.getNewFloat2(info.distance / 1000f));
//        }else {
//            if (SerialPortManager.mCurrentDeviceType == DeviceType.RUNNING_MACHINE) {
//                setText(R.id.tvKcal, Utils.getNewFloat(info.kcal * 1.0f / 1000));
//                setText(R.id.tvSteps, String.valueOf(info.steps));
//                setText(R.id.tvSpm, String.valueOf(0));
//                setText(R.id.tvSlope, Utils.getNewFloat(info.slop));
//                valY2 = Float.parseFloat(Utils.getNewFloat(info.slop));
////                lineChartUtils2.invalidate(info.time,Float.parseFloat(Utils.getNewFloat(info.slop)));
//                setText(R.id.tvSpeed, Utils.getNewFloat(info.speed / 10f));
//                setText(R.id.tvPace, info.speed == 0 ? "0" : Utils.getNewFloat2(60f / (info.speed / 10f)));   //计算多少分钟跑1公里
//            } else if (SerialPortManager.mCurrentDeviceType == DeviceType.CAR_WATCH) {
//                setText(R.id.tvKcal, Utils.getNewFloat(info.kcal * 0.1f));
//                setText(R.id.tvSteps, String.valueOf(info.count));
//                setText(R.id.tvSpm, String.valueOf(info.rpm));
//                setText(R.id.tvSlope, String.valueOf(info.slop));
//                valY2 = Float.parseFloat(String.valueOf(info.slop));
//                valY = Float.parseFloat(Utils.getNewFloat(info.speed*0.01f));
////                lineChartUtils2.invalidate(info.time,Float.parseFloat(String.valueOf(info.resistance)));
//                String text;
//                if (info.speed == 0) {
//                    text = "00:00";
//                } else {
//                    text = DateUtils.getInstance().speedAllocationConvertInto(info.speed);
//
//                }
//                setText(R.id.tvSpeed, text);
//                setText(R.id.tvPace, text);
//            }
//        }
        if (mTargetType == 0) {  //时间
            setText(R.id.tvNum, DateUtils.getInstance().secondConvertIntoTime(info.time));
        } else if (mTargetType == 1) {
            setText(R.id.tvNum, Utils.getNewFloat2(info.distance / 1000f));
        } else {
            setText(R.id.tvNum, Utils.getNewFloat(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL) ?
                    info.kcal * 1.0f / 1000 : info.kcal * 0.1f));
        }

        //折线图
        if(time < Math.round(info.time)){
            time = Math.round(info.time);
            if(info != null){
                lineChartUtils.invalidate(time,valY);
                lineChartUtils1.invalidate(time,info.heart);
                lineChartUtils2.invalidate(time,valY2);
                lineChartUtils3.invalidate(time,info.count);
            }
        }


        CircularProgressView progressView = findViewById(R.id.circularProgressView);
        if (mTargetNum <= 0) {
            progressView.setProgress((int) ((info.time % 60) * 100f / 60));
        } else {
            int progress = 0;
            switch (mTargetType) {
                case 0:
                    progress = (int) (info.time * 100f / mTargetNum / 60f);
                    break;
                case 1:
                    progress = (int) (info.distance / 1000f * 100f / mTargetNum);
                    break;
                case 2:
                    if (MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)) {
                        progress = (int) (info.kcal / 1000f * 100f / mTargetNum);
                    } else {
                        progress = (int) (info.kcal * 0.1 * 100f / mTargetNum);
                    }
                    break;
            }
            if (progress >= 100) {
                progress = 100;
                if (MotionDataUtils.getInstance().isRun() && !mIsTargetComplete) {
                    if (DataManager.Companion.getInstance().getMainStyle() == 3) {
                        DataManager.Companion.getInstance().setObject(FastBlurUtility.getBlurBackgroundDrawer(this));
                    }
                    Intent intent = new Intent(this, DialogActivity.class);
                    intent.putExtra(Constants.BUNDLE_EXTRA, DialogActivity.TARGET_COMPLETE);
                    startActivity(intent);
                }
                mIsTargetComplete = true;
            }
            progressView.setProgress(progress);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if ( map.containsKey(EventBusEvent.PAUSE_RUN)||map.containsKey(EventBusEvent.STOP_RUN)) {
            System.out.println("BluetoothOrder ------------->  STOP_RUN : 2");
            showStartBtn(false);
            BluetoothOrder.getInstance().uploadSportInfo(true);
            initWidget();
        }else if(map.containsKey(EventBusEvent.KILL_ACTIVITY)){
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put(EventBusEvent.STOP_RUN,"");
            EventBus.getDefault().post(map1);
            finish();
        }else {
            super.onReceive(map);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(DeviceTypeUtils.connectDeviceType() == 0){
            BluetoothOrder.getInstance().closeCurrentInfo();
        }

    }

    public void setViewsAlpha(float alpha, int... viewIds) {
    }

    @Override
    public boolean isMainActivity() {
        return false;
    }


}